<?php

declare(strict_types=1);

namespace app\model;

use app\common\facade\auth\Auth;
use app\common\model\JumpTypeMap;
use app\common\service\takeout\JtkTakeoutService;
use app\event\ChangePageSettingSuccess;
use app\model\base\BasePageSettingModel;
use app\model\PageSetting as PageSettingModel;
use Carbon\Carbon;
use think\db\BaseQuery;
use think\db\Query;
use think\facade\Cache;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 *
 *
 * @mixin \think\Model
 * @property int $id 主键id
 * @property int $agent_id 代理商id
 * @property string $setting_name 名称
 * @property string $image 图片
 * @property int $sort 排序desc
 * @property int $status 状态：1启用 2禁用
 * @property mixed $ext_data 扩展信息
 * @property int $type 1.外卖2.聚合模板 3 品牌权益
 * @property int $sub_category 子分类
 * @property int $source 1系统2自定义
 * @property int $position 首页轮播图位置 1头部 2中间
 * @property string $created_at 创建时间
 * @property string $updated_at 修改时间
 * @property string $deleted_at 删除时间，删除标识
 * @property string $old_image oss数据迁移，备份旧数据
 * @method static \think\db\Query onlyTrashed()
 * @method static \think\db\Query withTrashed()
 */
class PageSetting extends BasePageSettingModel
{
    use SoftDelete;

    protected $table = 'page_setting';

    //类别type
    const TYPE_TACKOUT      = 1;  //外卖系统
    const TYPE_LOCAL_LIFE   = 2;  //本地生活
    const TYPE_COUPON       = 3;  //品牌权益

    //状态
    const STATUS_ACTIVE = 1;  //启用
    const STATUS_CLOSE  = 2;  //禁用

    //子类型
    const SUB_CATEGORY_SYLBT = 1; //首页轮播图
    const SUB_CATEGORY_SYJGQ = 2; //首页金刚区
    const SUB_CATEGORY_DFK   = 3; //豆腐块

    //数据来源
    const SOURCE_SYSTEM = 1;      //系统
    const SOURCE_ZDY    = 2;      //自定义

    //轮播图位置
    const POSITION_HEAD = 1;   //头部
    const POSITION_MIDDLE = 2; //中间

    //agent_id = 0代表是系统配置
    const SYS_AGENT_ID = 0;

    const IS_SYS = true;

    // 设置json类型字段
    protected $json = ['ext_data'];

    //设置JSON数据返回数组
    protected $jsonAssoc = true;


    /**
     * @note 首页列表
     * @access public
     * @param $params array 参数
     * @return array|BaseQuery[]|\think\Collection|\think\Paginator
     */
    public function getList($params)
    {
        /**
         * @var BaseQuery $query
         */
        if (isset($params['agent_id'])) {
            $agent_id = $params['agent_id'];
        } else {
            $agent_id = Auth::agentId();
        }
        $cache_key = 'JumpTypeService_getJumpConfig_page_setting_key_cache_'.$agent_id.'_'.$params['type'].'_'.$params['sub_category'];
        if (Auth::platform() == 'api' && $agent_id > 0) {
            $list = Cache::get($cache_key);
            if ($list && !$list->isEmpty()) {
                return $list;
            }
        }
        $order = 'sort desc';
        $query = self::query()->withSearch(
            [
                'agent_id',
                'type',
                'sub_category',
                'status',
                'source',
                'position',
                'setting_name',
            ], $params)
            ->order($order)
            ->withoutField('deleted_at');
        if (Auth::platform() == 'api') {
            $list = $query->select();
            //八个小时的缓存
            Cache::set($cache_key, $list, 8*3600);
        } else {
            $list = $query->paginate();
        }
        return $list;
    }

    /**
     * 美团券包 活动过期的话 更新状态
     * @param PageSetting $obj
     * @return void
     */
    public function updateMeituanCoupon() {

        self::query()
            ->where('status', self::STATUS_ACTIVE)
//            ->withSearch(['status', 'agent_id'], $params)
            ->whereRaw("JSON_CONTAINS(ext_data, JSON_OBJECT('jump_type', ". JumpTypeMap::JUMP_TYPE_MEITUAN_COUPON."))" )
            ->where('act_end_date', '<>', '')
            ->select()->each(function (PageSettingModel $model) {
                $actEndTime = strtotime($model->act_end_date);
                if (!$actEndTime) { // strtotime转换不对，日期格式显然不对。
                    return false;
                }
                if (Carbon::now() >=  Carbon::parse($model->act_end_date)->endOfDay()) {
                    $model->status = self::STATUS_CLOSE;
                    $model->save();
                }
            });
    }

    /**
     * @note 新增/编辑保存
     * @access public
     * @param $params array 参数
     * @return \think\response\Json
     */
    public function doSave($params)
    {
//        $ext_data = array();
        $ext_data = $params;
        // 需要释放的几个字段, ps:已经有的字段释放 比如id对前端有影响
        $notExtDataField = [
            'id', 'setting_name', 'image', 'sort', 'position', 'sub_category'
        ];
        foreach ($notExtDataField as $field) {
            if (isset($ext_data[$field])) {
                unset($ext_data[$field]);
            }
        }
//        if (isset($params['jump_type'])) {
//            $ext_data['jump_type'] = $params['jump_type'];
//        }
//        if (isset($params['path'])) {
//            $ext_data['path'] = $params['path'];
//        }
//        if (isset($params['discount_logo'])) {
//            $ext_data['discount_logo'] = $params['discount_logo'];
//        }
//        if (isset($params['subtitle_type'])) {
//            $ext_data['subtitle_type'] = $params['subtitle_type'];
//        }
//        if (isset($params['subtitle'])) {
//            $ext_data['subtitle'] = $params['subtitle'];
//        }
//        if (isset($params['brand_id'])) {
//            $ext_data['brand_id'] = $params['brand_id'];
//        }
//        if (isset($params['act_id'])) {
//            $ext_data['act_id'] = $params['act_id'];
//        }
//        if (isset($params['activity_date'])) {
//            $ext_data['activity_date'] = $params['activity_date'];
//        }
//        if (isset($params['title'])) {
//            $ext_data['title'] = $params['title'];
//        }
        if ((!isset($params['image']) || empty($params['image'])) && $params['jump_type'] == 5) {
            $image = CouponBrand::query()->where('id', $params['brand_id'])->value('image_url');
        }
        //代理端
        if (Auth::platform() == 'agent') {
            $params['agent_id'] = Auth::agentId();
            if (isset($params['is_sys']) && $params['is_sys']) {
                $params['source'] = $params['source']??PageSettingModel::SOURCE_SYSTEM;
            } else {
                $params['source'] = $params['source']??PageSettingModel::SOURCE_ZDY;
            }
        }

        //总后台
        if (Auth::platform() == 'admin'){
            $params['agent_id'] = $params['agent_id']??0;
            $params['source']   = $params['source']??PageSettingModel::SOURCE_SYSTEM;
        }
        $data = [
            'agent_id'      => $params['agent_id']??0,
            'setting_name'  => $params['setting_name'],
            'image'         => $image??$params['image'],
            'sort'          => $params['sort']??0,
            'type'          => $params['type'],
            'sub_category'  => $params['sub_category'],
            'source'        => $params['source'],
            'position'      => $params['position']??0,
        ];
        if (isset($params['is_sys']) && $params['is_sys']) { //系统内部调用
            $data['ext_data'] = $params['ext_data'];
        } else { //方法调用
            $data['ext_data'] = $ext_data;
        }
        if (isset($data['ext_data']['activity_date'])) {
            $actDate = JtkTakeoutService::getInstance()->actDateRange($data['ext_data']['activity_date']);
            $data['act_start_date'] = $actDate[0] ?? '';
            $data['act_end_date'] = $actDate[1] ?? '';
        }
        if (isset($params['id']) && !empty($params['id'])) {
            $data['id'] = $params['id'];
            self::update($data);
            return $data['id'];
        } else {
            $info = self::create($data);
            return $info->id;
        }
    }

    /**
     * 系统同步
     * @access public
     * @param $params array 参数
     * @return \think\response\Json
     */
    public function sysnc($params)
    {
        //1.查询需要同步的总后台数据是否存在
        $list = self::query()->where('agent_id', self::SYS_AGENT_ID)
                             ->where('type', $params['type'])
                             ->where('sub_category', $params['sub_category'])
                             ->where('status', self::STATUS_ACTIVE)
                             ->where('source', self::SOURCE_SYSTEM)
                             ->select();
        if ($list->isEmpty()) {
            return fail('同步系统失败,系统暂无符合条件的配置');
        }
        //开启事务
        Db::startTrans();
        try {
            //2.同步后台数据
            $addArr = array();
            $list->each(function (PageSetting $pageSetting) use ($params, &$addArr){
                $data = $pageSetting->toArray();
                unset($data['id']);
                unset($data['agent_id']);
                $data['agent_id'] = $params['agent_id'];
                $data['is_sys'] = self::IS_SYS;
                $id = $this->doSave($data);
                array_push($addArr, $id);
            });
            //3.删除代理之前配置的数据
            self::destroy(function($query) use ($params,$addArr){
                /**
                 * @var BaseQuery $query
                 */
                $query->where('agent_id', $params['agent_id'])
                    ->where('type', $params['type'])
                    ->where('sub_category', $params['sub_category'])
                    //->where('source', self::SOURCE_ZDY)
                    ->whereNotIn('id', $addArr);
            });
            Db::commit();
            return success('同步系统成功');
        } catch (\Exception $e) {
            Db::rollback();
            return fail('同步系统失败：'.$e->getMessage());
        }
    }

    /**
     * 代理搜索
     */
    public function searchAgentIdAttr($query, $value, $data)
    {
        /**
         * @var Query $query
         */
        //代理需要看到自己的并且看到总后台设置的
        if (!empty($data['channel']) && $data['channel'] == AgentChannel::YMHC_ADMIN_CHANNEL)  {
            $query->where('agent_id', 0);
        } else {
            if (Auth::platform() == 'agent' || Auth::platform() == 'api') {
                $query->where('agent_id', Auth::agentId());
            } elseif(Auth::platform() == 'admin') {
                $query->where('agent_id', 0);
            }
        }

    }

    /**
     * 代理搜索
     */
    public function searchSettingNameAttr($query, $value, $data)
    {
        /**
         * @var Query $query
         */
        $setting_name = $data['setting_name']??'';
        if ($setting_name) {
            $query->where('setting_name', 'like', '%'.trim($setting_name).'%');
        }
    }

    /**
     * 状态搜索
     */
    public function searchStatusAttr($query, $value, $data)
    {
        $status = $data['status']??'';
        if ($status && in_array($status, [self::STATUS_ACTIVE, self::STATUS_CLOSE])) {
            $query->where('status', $status);
        }
    }

    /**
     * 类型搜索
     */
    public function searchTypeAttr($query, $value, $data)
    {
        $type = $data['type']??'';
        if ($type && in_array($type, [self::TYPE_TACKOUT, self::TYPE_LOCAL_LIFE, self::TYPE_COUPON])) {
            $query->where('type', $type);
        }
    }

    /**
     * 子类型搜索
     */
    public function searchSubCategoryAttr($query, $value, $data)
    {
        $sub_category = $data['sub_category']??'';
        if ($sub_category && in_array($sub_category, [self::SUB_CATEGORY_SYLBT, self::SUB_CATEGORY_SYJGQ, self::SUB_CATEGORY_DFK])) {
            $query->where('sub_category', $sub_category);
        }
    }

    /**
     * 来源
     */
    public function searchSourceAttr($query, $value, $data)
    {
        $source = $data['source']??'';
        if ($source && in_array($source, [self::SOURCE_SYSTEM, self::SOURCE_ZDY])) {
            $query->where('source', $source);
        }
    }

    /**
     * 轮播图位置搜索
     */
    public function searchPositionAttr($query, $value, $data)
    {
        $position = $data['position']??'';
        if ($position && in_array($position, [self::POSITION_HEAD, self::POSITION_MIDDLE])) {
            $query->where('position', $position);
        }
    }


    //重新生成缓存
    public static function onAfterUpdate($module)
    {
        /**
         * @var PageSetting $module
         */
        if ($module->agent_id > 0) {
            event(new ChangePageSettingSuccess($module));
        }
    }

    //重新生成缓存
    public static function onAfterInsert($module)
    {
        /**
         * @var PageSetting $module
         */
        if ($module->agent_id > 0) {
            event(new ChangePageSettingSuccess($module));
        }
    }

    //重新生成缓存
    public static function onAfterDelete($module)
    {
        /**
         * @var PageSetting $module
         */
        if ($module->agent_id > 0) {
            event(new ChangePageSettingSuccess($module));
        }
    }


}
